package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.RidesKey;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 保存手机号作为key,验证码作为value
     * @param phone
     * @param code
     */
    @Override
    public void sendVerifyCode(String phone,String code) {
        String join = RidesKey.VIREFY_CODE.join(phone);
        redisTemplate.opsForValue().set(join, code, RidesKey.VIREFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    /**
     * 用来判断验证码是否正确
     * @param
     * @return
     */
    @Override
    public String getVerifyCode(String phone) {
        String realVerifyCode = redisTemplate.opsForValue().get(RidesKey.VIREFY_CODE.join(phone));
        return realVerifyCode;
    }

    /**
     * 设置登录用户的信息存放在redis中,此时uuid作为key,user作为value
     * @param userInfo
     * @return
     */
    @Override
    public String setUserToken(UserInfo userInfo) {
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(RidesKey.USER_TOKEN_REDIS.join(key), JSON.toJSONString(userInfo), Consts.VERIFY_CODE_VAI_TIME * 60L, TimeUnit.SECONDS);
        return key;
    }

    /**
     * 获取token中的user对象
     * @param token
     * @return
     */
    @Override
    public UserInfo getUserByToken(String token) {
        //先判断是否有token传过来
        if (!StringUtils.hasLength(token)){
            return null;
        }

        //先判断是否还存在当前key
        String key = RidesKey.USER_TOKEN_REDIS.join(token);
        if (redisTemplate.hasKey(key)){
            String userInfo = redisTemplate.opsForValue().get(key);
            UserInfo info = JSON.parseObject(userInfo, UserInfo.class);

            //重置有效时间
            redisTemplate.expire(key, Consts.VERIFY_CODE_VAI_TIME * 60L, TimeUnit.SECONDS);

            return info;
        }
        return null;
    }


}
